/*
 *  Copyright 2011 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.vcforms.transform_t2d.text.sheet;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author yura
 */
public class SheetSet {

    private LineCollector lineCollector;
    private Iterator<String> unresolvedStrings;
    private List<Sheet> sheets;
    
    public SheetSet(LineCollector lineCollector, String text) {
        this.lineCollector = lineCollector;
        this.unresolvedStrings = lineCollector.split(text).iterator();
        this.sheets = new ArrayList<Sheet>();
    }

    /**
     * Calculate the number of current page, starting from <b>1</b>.
     * @return the number of current page.
     */
    public int getCurrentPage() {
        return sheets.size() + 1;
    }

    /**
     * Checking the resolving of the all text
     * @return true if there is no more unresolved text.
     */
    public boolean needMore(){
        return unresolvedStrings.hasNext();
    }

    /**
     * Add new page with defined header and with defined number of lines.
     * The lines taken from text that was given at creation of current object.
     * As much line, this set will use, so much lines in given text will be
     * resolved.
     * @param linNumber number of lines that necessary for the new sheet
     * @param header header of the new sheet (It's can be null).
     * @return new sheet
     */
    public Sheet resolvePage(int linNumber, String header, String footer){
        Sheet sheet = new Sheet(lineCollector);

        if (header != null){
            sheet.getHeader().addAll(lineCollector.split(header));
        }

        if (footer != null){
            sheet.getFooter().addAll(lineCollector.split(footer));
        }
        
        List<String> body = sheet.getBody();
        for (; unresolvedStrings.hasNext() && linNumber > 0; linNumber--) {
            body.add(unresolvedStrings.next());
        }

        sheets.add(sheet);

        return sheet;
    }

    /**
     * @see #needMore()
     * @see #resolvePage(int, String)
     * @throws IllegalStateException if unresolved text still not resolved
     */
    @Override
    public String toString() {
        if (unresolvedStrings.hasNext()){
            throw new IllegalStateException("Unresolved text still not resolved");
        }

        return lineCollector.collect(sheets);
    }

}
